package com.catmiw.funds.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.catmiw.funds.dao.CompanyMapper;
import com.catmiw.funds.domain.Company;
import com.catmiw.funds.tool.DataLoader;

public class CompanyServiceImpl implements CompanyService {
	public int insertAll(List<Company> companys) {
		SqlSession session=SessionFactory.getInstance().getSession();
		
		CompanyMapper cm=session.getMapper(CompanyMapper.class);
		List<Company> old=cm.selectAll();
		int count=0;
		for (Company c:companys){
			System.out.println(c);
			if (old.contains(c)){
				cm.update(c);
			} else {
				cm.insert(c);
				count++;
			}
		}
		session.commit();
		session.close();
		
		return count;
	}

	private static void test(){
		SqlSession session=SessionFactory.getInstance().getSession();
		CompanyMapper cm=session.getMapper(CompanyMapper.class);

		List<Company> old=cm.selectAll();
		for (Company c:old){
			System.out.println(c);
		}
		session.close();
	}
	
	public static void main(String[] args) {
		List<Company> lc=DataLoader.getCompanys();
		CompanyService cs=new CompanyServiceImpl();
		cs.insertAll(lc);
		test();

	}

	public List<Company> selectAll() {
		SqlSession session=SessionFactory.getInstance().getSession();
		
		CompanyMapper cm=session.getMapper(CompanyMapper.class);
		List<Company> old=cm.selectAll();

		session.close();
		return old;
	}

	public Company select(String code) {
		SqlSession session=SessionFactory.getInstance().getSession();
		
		CompanyMapper cm=session.getMapper(CompanyMapper.class);
		Company company=cm.select(code);

		session.close();
		
		return company;
	}

}
